<template>
  <div class="loginDiv">
    <div id="loginBack">
      <img id="backlogo" src="@/assets/images/login_bg.png"/>
    </div>
    <div class="loginForm">
      <el-tabs type="card" v-model="activeName">
        <el-tab-pane label="用户登录" name="userlogin">
          <el-form ref="form" label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="loginUser.identify" placeholder="请输入注册手机/邮箱/账号"></el-input>
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="loginUser.password" placeholder="请输入密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="" style="margin-bottom: 0px">
              <drag-verify-img-chip ref="dragVerify" :width="260" :height="38" :imgsrc="imgsrc"
                                    :isPassing.sync="isPassing" :showRefresh="true"
                                    :barWidth="40" text="请按住滑块拖动" successText="验证通过"
                                    handlerIcon="el-icon-d-arrow-right"
                                    successIcon="el-icon-circle-check" :refreshIcon="'el-icon-refresh-right'"
                                    @refresh="reset" @passcallback="pass">
              </drag-verify-img-chip>

              记住我
              <el-switch
                  v-model="rememberme"
                  active-color="#13ce66"
                  inactive-color="#ff4949">
              </el-switch>
              <div style="display: inline;vertical-align: middle">&nbsp;&nbsp;第三方登录 <a href="#"><img
                  src="@/assets/images/QQ_logo.png" style="width:22px;vertical-align: middle;cursor: pointer;"></a> <img
                  src="@/assets/images/weixni_logo.png" style="width:22px;vertical-align: middle;cursor: pointer;">
              </div>
            </el-form-item>

            <el-form-item label="">
              <el-button style="width: 80%; display: block" @click="doLogin" type="primary" plain>登录
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="用户注册" name="userreg">
          <el-form ref="form" label-width="100px">
            <el-form-item label="用户名">
              <el-input v-model="regUser.identify" placeholder="请输入注册手机/邮箱"></el-input>
            </el-form-item>
            <el-form-item label="">

              <el-button @click="debounceSendMsgToMobileOrEmail" :disabled="sendMsgDisabled">{{
                  sendMsgBtnTitle
                }}
              </el-button>
              <!--
              <img src="../../assets/images/vcode.png" title="看不清楚，换一张" style="cursor:pointer" @click="changeRandomCodeImg">
              -->
            </el-form-item>
            <el-form-item label="密码">
              <el-input v-model="regUser.password" placeholder="请输入密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="确认密码">
              <el-input v-model="regUser.confirmpass" placeholder="请输入确认密码" show-password></el-input>
            </el-form-item>
            <el-form-item label="验证码">
              <el-input v-model="regUser.validateCode" placeholder="请输入验证码"></el-input>
            </el-form-item>
            <el-form-item label="">
              <el-button style="width: 80%; display: block" type="success" @click="doReg" plain>注册
              </el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
      </el-tabs>
    </div>
  </div>
</template>

<script>
//滑块验证组件
import dragVerifyImgChip from 'vue-drag-verify-img-chip'
//对axios的简单的封装
import request from "@/util/request";
import http from "@/util/http";
//生成客户端令牌(token)的插件
import webtoken from "@/util/webtoken";
//鲁大师工具类
import _ from 'lodash';

//前端的用户业务逻辑接口
import {reg, login, checkIsReg} from '@/api/users/users'

//前端的crypto加密库
import {encrypt, decrypt} from "@/util/crypto";

// 完整引入outils工具类
const outils = require('outils');
export default {
  name: "MyLoginForm",
  components: {
    dragVerifyImgChip
  },
  data() {
    return {
      sendMsgDisabled: false,
      sendMsgBtnTitle: '发送验证码',
      isPassing: false,
      value: "",
      imgsrcList: ["https://img.simoniu.com/huakuai01.jpg", "https://img.simoniu.com/huakuai02.jpg", "https://img.simoniu.com/huakuai03.jpg", "https://img.simoniu.com/huakuai04.jpg", "https://img.simoniu.com/huakuai05.jpg"],
      imgsrc: '',
      activeName: "userlogin",
      token: '', //客户产生的令牌
      rememberme: true,
      loginUser: {
        identify: '',
        password: ''
      },
      loginSuccessUser: {}, //登录成功的用户对象
      regUser: {
        identify: "", //输入的电子邮箱或者手机号码
        email: "",
        mobile: "",
        password: "",
        confirmpass: "",
        validateCode: "",
        flag: 1
      },
    }

  },
  mounted() {
    this.imgsrc = this.imgsrcList[Math.floor(Math.random() * 5)]
    //生成一个客户端的前端令牌。
    this.token = webtoken.generateWebToken();
    console.log("客户端产生的令牌是：" + this.token);

    this.initLoginUsersIdentify();
  },
  methods: {

    initLoginUsersIdentify(){
      if(outils.getCookie("mysite_identify")){
        let encodeIdentify = outils.getCookie("mysite_identify");
        this.loginUser.identify = decrypt(encodeIdentify);
        let encodePass = outils.getCookie("mysite_password");
        this.loginUser.password = decrypt(encodePass);
      }
    },

    reimg() {

    },
    pass() {

    },
    reset() {
      this.imgsrc = this.imgsrcList[Math.floor(Math.random() * 5)];
      this.isPassing = false;
      this.$refs.dragVerify.reset()
    },
    verify(result) {
      console.log(result) // result为true表示验证通过，false表示验证三次都失败了哦
      this.huakuaiFlag = result;
    },
    refresh() {
      console.log('用户点击了初始化')
    },

    changeTab(tabName) {
      this.activeName = tabName;
    },
    //用户登录
    doLogin() {
      //this.v
      //首先判断滑块拼图是否正确
      if (!this.isPassing) {
        this.$message({
          message: '滑块验证失败！',
          type: "error"
        });
        return;
      }

      //console.log('执行用户登录....')
      let params = {
        identify: this.loginUser.identify,
        password: this.loginUser.password
      }

      login(params).then(resp => {
        //console.log(resp);
        if (resp.data.code === 400 || resp.data.code === 500) {
          this.$message({
            message: resp.data.msg,
            type: "error"
          });
        } else {
          this.$message({
            message: resp.data.msg,
            type: "success"
          });

          /*
          let token_name = resp.data.data.tokenName
          let token_value = resp.data.data.tokenValue;
          //保存到cookie;
          outils.setCookie("satoken", token_value, 100); //默认保存100天
          */

          let obj = resp.data.data;
          obj.tokenName = "";
          obj.tokenValue = "";

          localStorage.setItem("currentLoginUserInfo", JSON.stringify(obj));// resp.data.data;
          sessionStorage.setItem("currentLoginStatus", true);

          //判断用户是否选择了记住我。
          if (this.rememberme) {
            let encodeIdentify = encrypt(this.loginUser.identify);
            let encodePass = encrypt(this.loginUser.password);
            outils.setCookie("mysite_identify", encodeIdentify,100);
            outils.setCookie("mysite_password", encodePass,100);
          } else {
            outils.removeCookie("mysite_identify");
            outils.removeCookie("mysite_password");
          }

          //延迟1秒钟后，自动跳转首页。
          setTimeout('window.location.href="/"', 1000);

        }
      })
    },

    //注册表单的表单验证
    async regFormValiateCheck(type) {

      //console.log('执行表单验证....')
      if (!outils.isPhoneNum(this.regUser.identify) && !outils.isEmail(this.regUser.identify)) {
        this.$message({
          message: '用户注册信息格式非法',
          type: "error"
        });
        return false;
      }

      if (type === 'reg') {
        //检查用户密码是否小于6位。
        if (this.regUser.password.length < 6) {
          this.$message({
            message: '密码长度不能少于6位',
            type: "error"
          });
          return false;
        }

        if (this.regUser.password !== this.regUser.confirmpass) {
          this.$message({
            message: '密码和确认密码不一致',
            type: "error"
          });
          return false;
        }
      }
      return true;
    },

    async doReg() {
      //console.log('执行用户注册');
      //首先检查验证码是否通过。
      if (!await this.regFormValiateCheck('reg')) {
        return;
      }

      if (!await this.checkValidateCode()) {
        //console.log('继续执行用户注册...')
        console.log('验证不正确.....')
        return;
      }
      console.log('继续执行用户注册,完整的用户信息如下：');
      if (outils.isPhoneNum(this.regUser.identify)) {
        this.regUser.mobile = this.regUser.identify;
      }
      if (outils.isEmail(this.regUser.identify)) {
        this.regUser.email = this.regUser.identify;
      }
      console.log(this.regUser);

      //调用后端的用户注册接口， 把用户资料保存到mysql数据库中。
      reg(this.regUser).then(resp => {
        console.log(resp);
        if (resp.data.code === 200) {
          this.$message({
            message: resp.data.msg,
            type: "success"
          });

          //注册成功之后，延迟一秒钟，自动切换到用户登录的tab;
          setTimeout(() => this.changeTab('userlogin'), 1000);
        }
      })

    },
    changeRandomCodeImg() {
      console.log('执行更换验证码图片....');
    },
    //检查电子邮箱或者手机号码是否已经被注册
    async checkIdentifyIsReg() {

      return false;
    },

    //防抖实现发送手机验证码.
    debounceSendMsgToMobileOrEmail: _.debounce(function () {
      this.sendMsgToMobileOrEmail()
    }, 1000),

    //给手机或者电子邮箱发送验证码
    async sendMsgToMobileOrEmail() {
      //console.log('发送手机验证码....');
      //发送验证码之前也必须进行表单验证
      if (!await this.regFormValiateCheck('msg')) {
        return;
      }

      //表单验证完成之后，检查该手机号码或者电子邮箱是否已经注册。
      let params = {
        identify: this.regUser.identify
      };

      let isRegFlag = await checkIsReg(params).then(resp => {
        return resp.data.data;
      });

      if (isRegFlag) {
        this.$message({
          message: '该账号已被注册！',
          type: "error"
        });
        return;
      }

      //这里要调用发送验证码的公网的接口。
      request.get("https://www.simoniu.com/commons/msg/validatecode", {
        params: {
          token: this.token,
          identify: this.regUser.identify
        }
      }).then(resp => {
        if (resp.data.code === 200) {
          this.$message({
            message: resp.data.msg,
            type: "success"
          });

          //一分钟之内不允许重复发送验证码。
          //发送成功之后，倒计时60秒，才能重新发送验证码。
          this.sendMsgDisabled = true;
          setTimeout(() => {
            this.sendMsgDisabled = false
          }, 60000);

          let iCount = 60;
          let timer = setInterval(() => {
            this.sendMsgBtnTitle = '发送验证码(' + (--iCount) + ')';
            //清除定时器
            if (iCount <= 0) {
              clearInterval(timer);
              this.sendMsgBtnTitle = '发送验证码'
            }
          }, 1000);
        }
      })
    },

    //检查验证码
    async checkValidateCode() {

      let flag = await request.get("https://www.simoniu.com:18991/examdemo/commons/msg/auth", {
        params: {
          token: this.token,
          code: this.regUser.validateCode
        }
      }).then(resp => {
        if (resp.data.code === 200) {
          //this.$message.success(resp.data.msg);
          return true;
        } else {
          this.$message({
            message: resp.data.msg,
            type: "error"
          });
          return false;
        }
      })

      return flag;
    }
  }
}
</script>

<style scoped>

.loginDiv {
  width: 100%;
  height: 520px;
  margin: 0px auto;
  background: lightblue;
  display: flex;
  justify-content: space-around;
}

#backlogo {
  margin: 40px 0 0 0px;
}

.loginForm {
  margin: 20px;
  background: #FFFFFF;
  width: 480px;
  border-radius: 0px;
}

.el-form-item {
  text-align: start;
}

.el-input {
  width: 280px;
}

.verifybox {
  display: flex;
}
</style>
